<template>
  <div class="bigbox">
    <!-- 搜索功能组件 -->
    <SearchBar @onSearch="onSearch" ref="searchBar"></SearchBar>
    <!-- 重置按钮 -->
    <el-form-item>
      <el-button type="primary" @click="resetSearch">重置</el-button>
      <el-button type="warning" @click="addArticle">新增</el-button>
    </el-form-item>
    <!-- 新增商品按钮 -->
  </div>
  <div>
    <el-table :data="tableData" stripe style="width: 100%" highlight-current-row
      :header-cell-style="{ background: '#def2fb', color: '#000' }" max-height="700">
      <el-table-column align="center" prop="author" label="作者" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="bookname" label="书名" :show-overflow-tooltip="true" />
      <!-- <el-table-column align="center" prop="content" label="内容" :show-overflow-tooltip="true"/> -->
      <el-table-column align="center" prop="status" label="是否显示" :show-overflow-tooltip="true">
        <template #default="scope">
          <div>
            {{ scope.row.status == 1 ? "显示" : "隐藏" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="Category" label="分类">
        <template #default="scope">
          <div>
            {{ scope.row.Category == 1 ? "文学" : "理学" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createtime" label="创建时间" :formatter="formatDate">
      </el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <el-button size="small" type="primary" @click="lookArticle(scope.row.id)">查看</el-button>
            <el-button size="small" type="warning" @click="editArticle(scope.row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteArticle(scope.row.id)">删除</el-button>
            <el-button @click="goWangContent(scope.row.id)" type="info" size="small">查看内容</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" @prev-click="getList()" @next-click="getList()" background v-model:page-size="pageSize" v-model:current-page="page"
      layout="prev, pager, next,sizes" :total="total" />

    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form ref="articleForm" :model="form" :rules="rules" @submit.native.prevent="onSubmit">
        <el-form-item label="作者" prop="author" :label-width="formLabelWidth">
          <el-input :disabled="disabled" v-model="form.author" autocomplete="on" />
        </el-form-item>
        <el-form-item label="书名" prop="bookname" :label-width="formLabelWidth">
          <el-input :disabled="disabled" v-model="form.bookname" autocomplete="on" />
        </el-form-item>
        <el-form-item label="是否显示" prop="status" :label-width="formLabelWidth">
          <el-select :disabled="disabled" v-model="form.status" placeholder="请选择是否显示">
            <el-option v-for="(item, index) in showOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="Category" :label-width="formLabelWidth">
          <el-select :disabled="disabled" v-model="form.Category" placeholder="请选择分类">
            <el-option v-for="(item, index) in CategoryOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer v-if="title != '查看文章'">
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import SearchBar from "../../components/SearchBar.vue";
import {
  ArticleListApi,
  ArticleDeleteApi,
  ArticleDetailApi,
  ArticleEditApi,
  ArticleSearchApi,
  ArticleAddApi
} from "../../api/index";
import router from "@/router";
export default {
  name: "CateList",
  components: {
    SearchBar,
  },

  data() {
    return {
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      dialogFormVisible: false,
      title: "",
      form: {},
      formLabelWidth: 80,
      rules: {
        author: [{ required: true, message: "作者不能为空", trigger: "blur" }],
        bookname: [
          { required: true, message: "书名不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "是否显示不能为空", trigger: "blur" },
        ],
        Category: [
          { required: true, message: "类型不能为空", trigger: "blur" },
        ],
      },
      disabled: false,
      showOptions: [
        {
          label: "显示",
          value: 1,
        },
        {
          label: "隐藏",
          value: 0,
        },
      ],
      CategoryOptions: [
        {
          label: "文学",
          value: 1,
        },
        {
          label: "理学",
          value: 0,
        },
      ],
      search: {},
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    //这个是监听到一页展示多少条数据的控制监听函数
    handleSizeChange(val) {
      console.log(val);
      this.pageSize = val;
      this.getList();
    },
    //这个是监听点击哪一页就跳转到哪一页的监听函数
    handleCurrentChange(number){
      console.log(number);
      this.page = number;
      this.getList()
    },
    goWangContent(id) {
      this.$router.push({ path: '/wangcontent', query: { id: id } })
    },
    resetForm() {
      this.form = {}
    },
    addArticle() {
      this.title = "新增文章";
      this.dialogFormVisible = true;
      this.disabled = false;
      this.resetForm()
    },
    resetSearch() {
      this.$refs.searchBar.reset();
      this.getList();
    },
    onSearch(search) {
      this.search = search;
      this.getSearch(this.search);
    },
    getSearch(val) {
      ArticleSearchApi(val).then((res) => {
        console.log(res);
        if (res.data.code == 1) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        } else {
          this.$message.error({
            type: "warning",
            message: res.data.msg,
          });
        }
      });
    },
    //日期格式化
    formatDate(value) {
      const date = new Date(value.createtime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    getList() {
      ArticleListApi({
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        console.log(res);
        if (res.data.code == 1) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
        if (res.data.code == 401) {
          this.$message({
            type: "error",
            message: res.data.msg,
            duration: 1000,
            onClose: () => {
              router.replace("/login");
            },
          });
        }
      });
    },
    deleteArticle(id) {
      //这里加一层modle判断确认是否删除
      this.$confirm("确认要删除这篇文章吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          ArticleDeleteApi({ id: id }).then((res) => {
            console.log(res);
            if (res.data.code == 1) {
              this.$message({
                type: "success",
                message: res.data.msg,
                duration: 1500,
                onClose: () => {
                  this.getList();
                },
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log("用户点击了取消");
        });
    },
    editArticle(id) {
      this.title = "修改文章";
      this.dialogFormVisible = true;
      this.disabled = false;
      ArticleDetailApi(id).then((res) => {
        if (res.data.code == 1) {
          this.form = res.data.data;
        } else {
          this.$message({
            type: "error",
            message: "获取数据失败",
          });
        }
      });
    },
    onSubmit() {
      this.$refs.articleForm.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            ArticleEditApi(this.form).then((res) => {
              console.log(res, "修改");
              if (res.data.code == 1) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1500,
                  onClose: () => {
                    this.getList();
                    this.dialogFormVisible = false;
                  },
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            });
          } else {
            ArticleAddApi(this.form).then(res => {
              if (res.data.code == 1) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1500,
                  onClose: () => {
                    this.getList();
                    this.dialogFormVisible = false;
                  },
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            })
          }
        } else {
          this.$message({
            type: "warning",
            message: "请填写完整信息",
          });
        }
      });
    },
    lookArticle(id) {
      this.title = "查看文章";
      this.dialogFormVisible = true;
      this.disabled = true;
      ArticleDetailApi(id).then((res) => {
        if (res.data.code == 1) {
          this.form = res.data.data;
        } else {
          this.$message({
            type: "error",
            message: "获取数据失败",
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.bigbox {
  display: flex;
  background-color: white;
  padding-top: 20px;
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
}
</style>
